import { createRouter, createWebHashHistory } from 'vue-router'
import { staticRouter, errorRouter } from './staticRouter.ts'
import NProgress from '@/config/nprogress.ts'
import { LOGIN_URL } from '@/config/config.ts'
import { useStore } from '@/store/index.ts'
import { initDynamicRouter } from '@/router/dynamicRouter.ts'
const routes = [...staticRouter, ...errorRouter] as any

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})
/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  const { global } = useStore() as { global: any }
  NProgress.start()
  document.title = to.meta.title ? `${to.meta.title}` : document.title
  // 访问登录页时，如果有token,清除token
  if (to.path === LOGIN_URL) {
    if (global.token) {
      global.setToken('')
    }
    // 重置路由
    resetRouter()
    return next()
  }
  const { auth } = useStore() as { auth: any }
  auth.setRouteName(to.name as string)
  // 动态路由，防止刷新时，路由丢失
  if (!auth.authMenuListGet.length) {
    await initDynamicRouter()
    return next({ ...to, replace: true })
  }
  next()
})

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done()
})

/**
 * @description 重置路由
 * */
export const resetRouter = () => {
  const { auth } = useStore() as { auth: any }
  auth.flatMenuListGet.forEach((route: any) => {
    const { name } = route
    if (name && router.hasRoute(name)) router.removeRoute(name)
  })
}
export default router
